<template>
  <div class="app-container search-list">
    <!-- PC端视图 -->
    <div v-if="!isMobile">
      <div class="el-form search-table-form" style="padding-bottom: 10px">
        <div class="el-row single-input">
          <div class="el-col el-col-24 el-col-md-8" style="justify-content: inherit">
            <el-date-picker
                size="small"
                v-model="dataDates"
                type="daterange"
                range-separator="~"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期" @change="changeDataTime">
            </el-date-picker>
            <div style="margin-left:20px;padding: 0">
              <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-search"
                  :loading="submitLoading"
                  @click="searchHandler"
              >
                查询
              </el-button>
              <el-button
                  type="primary"
                  :plain="false"
                  size="small"
                  icon="el-icon-refresh"
                  :loading="submitLoading"
                  @click="resetForm"
              >
                重置
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <table-pagination
          :showOperatingButton="false"
          ref="el-search-table"
          show-summary
          :summary-method="getSummaries"
          :fetch="getData"
          type="remote"
          :adaptive="fixOption"
          :page-sizes="[20, 50, 100]"
          :columns="columns"
          :form-options="formOptions"
          list-field="records"
          total-field="totalElements"
          page-index-key="page"
          page-size-key="pageSize"
          height="300"
          method="get">
      </table-pagination>
    </div>

    <!-- 移动端视图 -->
    <mobile-sale-list v-else :siteId="siteId" />
  </div>
</template>

<script>
import TablePagination from '_c/Tables/table-pagination';
import MobileSaleList from '@/components/MobileSaleList';
import {getSalePage} from '@/api/stat-core';
import {currency, utcFormat} from '@/utils/filters';
import {mapGetters} from 'vuex';

export default {
    name: 'sale-list',
    components: {
        TablePagination,
        MobileSaleList
    },
    data () {
        return {
            submitLoading: false,
            dataDates: [],
            fixOption: {fixedHeader: true},
            startTime: null,
            finishTime: null,
            pageParams: {
                page: 1,
                pageSize: 20,
                startTime: '',
                endTime: ''
            },
            formOptions: {
                showResetBtn: true,
                showSearchBtn: true,
                inline: false,
                labelWidth: 120,
                submitBtnText: '查询',
                size: 'small',
                resetBtnCallback: () => {
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                },
                forms: []
            },
            columns: [
                {
                    label: '时间',
                    prop: 'recordTime',
                    render: row => {
                        if (row.recordDate) {
                            return row.recordDate;
                        } else {
                            return utcFormat(row.recordTime, 'YYYY-MM-DD HH:00:00', this.timeZone);
                        }
                    }
                },
                {label: '订单数', prop: 'orderQty'},
                {label: '销售商品数', prop: 'skuQty'},
                {
                    label: '销售额',
                    prop: 'salesAmount',
                    render: row => {
                        return currency(row.salesAmount, this.currencySymbol);
                    }
                },
                {
                    label: '折扣',
                    prop: 'discountAmount',
                    render: row => {
                        return currency(row.discountAmount, this.currencySymbol);
                    }
                },
                {
                    label: '运费',
                    prop: 'freightAmount',
                    render: row => {
                        return currency(row.freightAmount, this.currencySymbol);
                    }
                },
                {
                    label: '税费',
                    prop: 'taxAmount',
                    render: row => {
                        return currency(row.taxAmount, this.currencySymbol);
                    }
                },
                {
                    label: '总成交额',
                    prop: 'dealAmount',
                    render: row => {
                        return currency(row.dealAmount, this.currencySymbol);
                    }
                },
                {
                    label: '客单价',
                    prop: 'customerUnitPrice',
                    render: row => {
                        return currency(row.customerUnitPrice, this.currencySymbol);
                    }
                },
                {label: '连带率', prop: 'joinRate'}

            ]
        };
    },
    created () {
        this.initData();
    },
    methods: {
        initData () {
            let now = new Date();
            let tempMonth = (100 + now.getMonth() + 1).toString().substring(1);
            let tempDay = (100 + now.getDate()).toString().substring(1);
            let tempDate = now.getFullYear() + '/' + tempMonth + '/' + tempDay;
            this.dataDates = [tempDate, tempDate];
            this.pageParams.startTime = new Date(tempDate + ' 00:00:00 UTC' + this.timeZone).getTime();
            this.pageParams.endTime = new Date(tempDate + ' 23:59:59 UTC' + this.timeZone).getTime();
        },
        getData (params) {
            this.pageParams.siteId = this.siteId;
            return new Promise((resolve, reject) => {
                getSalePage({...this.pageParams, ...params}).then((res) => {
                    resolve(res);
                });
            });
        },
        getSummaries (param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value)) && index !== 8 && index !== 9) {
                    const sumVal = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] = (index !== 0 && index !== 1 && index !== 2) ? currency(sumVal, '$') : sumVal;
                } else {
                    sums[index] = '';
                }
                this.$nextTick(() => {
                    this.$refs['el-search-table'].doLayout();
                });
            });

            return sums;
        },
        getSiteTimeZoneStartTime (startTime) {
            if (startTime === undefined || startTime == null || startTime === '') {
                return startTime;
            }
            let tempTime = new Date(startTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 00:00:00 UTC' + this.timeZone;
            return new Date(timeZoneStr).getTime();
        },
        getSiteTimeZoneEndTime (endTime) {
            if (endTime === undefined || endTime == null || endTime === '') {
                return endTime;
            }
            let tempTime = new Date(endTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 23:59:59 UTC' + this.timeZone;
            return new Date(timeZoneStr).getTime();
        },
        changeDataTime () {
            if (!this.dataDates || this.dataDates.length <= 0) {
                this.initData();
            } else {
                this.pageParams.startTime = new Date(this.dataDates[0].replace(/-/g, '/') + ' 00:00:00 UTC' + this.timeZone).getTime();
                this.pageParams.endTime = new Date(this.dataDates[1].replace(/-/g, '/') + ' 23:59:59 UTC' + this.timeZone).getTime();
                this.searchHandler();
            }
        },
        searchHandler () {
            this.$refs['el-search-table'].searchHandler(false);
        },
        resetForm () {
            this.initData();
            this.$refs['el-search-table'].fetchHandler({
                page: 1,
                pageSize: 20
            }, false);
        }
    },
    computed: {
        ...mapGetters([
            'timeZone',
            'siteList',
            'isMobile'
        ]),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        currencySymbol () {
            return this.siteInfo.currencySymbol;
        }
    }
};
</script>

<style scoped lang="scss">
.search-list {
  h4 {
    border-bottom: 1px solid #E8E8E8;
    margin: 0;
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .app-container {
    padding: 10px !important;
  }
}
</style>
